package com.ferry.common.util.concurrent;

import io.netty.util.concurrent.FastThreadLocalThread;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by daiyong
 */
public class NamedThreadFactory implements ThreadFactory{

	private AtomicInteger id = new AtomicInteger();
	private String name;
	private boolean daemon;
	private int priority;
	private ThreadGroup threadGroup;

	public NamedThreadFactory(String name) {
		this(name, false, Thread.NORM_PRIORITY);
	}

	public NamedThreadFactory(String name, boolean daemon) {
		this(name, daemon, Thread.NORM_PRIORITY);
	}

	public NamedThreadFactory(String name, boolean daemon, int priority) {
		this.name = name + "-";
		this.daemon = daemon;
		this.priority = priority;
		SecurityManager s = System.getSecurityManager();
		threadGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
	}

	/**
	 * 使用netty 的 FastThreadLocalThread
	 * @param r
	 * @return
	 */
	@Override
	public Thread newThread(@NotNull Runnable r) {
		Thread t = new FastThreadLocalThread(threadGroup, r, name);
		t.setDaemon(daemon);
		t.setPriority(priority);
		return t;
	}



}
